package com.deyun.charpt01

import com.deyun.charpt01.async.DownloadContext
import com.deyun.charpt01.async.我要开始加载图片
import com.deyun.charpt01.async.我要开始协程了
import com.deyun.charpt01.async.我要进行耗时操作
import javax.swing.JFrame.EXIT_ON_CLOSE


const val LOGO_URL = "http://www.imooc.com/static/img/index/logo.png?t=1.1"

fun main(args: Array<String>) {
    val frame= MainWindow()
    frame.title="图片"
    frame.setSize(300,250)
    frame.isResizable=true
    frame.defaultCloseOperation=EXIT_ON_CLOSE

    frame.init()
    frame.isVisible=true

    frame.onButtonClick {
        我要开始协程了(DownloadContext(LOGO_URL)) {
            try {
                val imageData = 我要进行耗时操作 {
                    我要开始加载图片(this[DownloadContext]!!.url)
                }
                frame.setLogo(imageData)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

//    frame.onButtonClick {
//        HttpService.service.getLogo(LOGO_URL)
//                .enqueue(object :Callback<ResponseBody>{
//                    override fun onResponse(
//                            call: Call<ResponseBody>,
//                            response: Response<ResponseBody>) {
//                        if (response.isSuccessful) {
//                            val imageData = response.body()?.byteStream()?.readBytes()
//                            if (imageData == null) {
//                                throw IllegalArgumentException(HttpError.HTTP_ERROR_NO_DATA.toString())
//                            } else {
//                                SwingUtilities.invokeLater {
//                                    frame.setLogo(imageData)
//                                }
//                            }
//                        } else {
//                            throw IllegalArgumentException(""+response.code())
//                        }
//                    }
//
//                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//                        throw IllegalArgumentException(HttpError.HTTP_ERROR_UNKNOWN.toString())
//                    }
//                })
//    }
}